package com.example.fun.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.fun.R;
import com.example.fun.bean.LoginBean;
import com.example.fun.bean.MineBean;
import com.example.fun.fragment.HomeFragment;
import com.example.fun.fragment.MineFragment;
import com.google.gson.Gson;

import java.io.IOException;
//import java.util.logging.Handler;


import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "LoginActivity";
    private Button btnLogin;
    private TextView tvRegister;
    private EditText edName;
    private EditText edPwd;
    private String token;
    private int loginStatus;
    private Intent intent = null;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg == obtainMessage()) {
                Toast.makeText(LoginActivity.this, "登录成功！", Toast.LENGTH_LONG).show();
            }
        }
    };

    @Override

    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        initView();
    }

    private void initView() {
        btnLogin = (Button) findViewById(R.id.btn_login);
        tvRegister = (TextView) findViewById(R.id.tv_registered);
        edName = (EditText) findViewById(R.id.ed_name);
        edPwd = (EditText) findViewById(R.id.ed_pwd);
        btnLogin.setOnClickListener(this);
        tvRegister.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                Login();
                break;
            case R.id.tv_registered:
                intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }

    }

    private void Login() {
        final String username = edName.getText().toString().trim();
        final String password = edPwd.getText().toString().trim();
        if (TextUtils.isEmpty(username)) {
            Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
            return;
        } else if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
            return;
        } else if (true) {
//            OkHttpClient client = new OkHttpClient();
//            final JSONObject jsonObject = new JSONObject();
//            try {
//                jsonObject.put("username", username);
//                jsonObject.put("password", password);
//            }catch (JSONException e){
//                e.printStackTrace();
//            }
//            MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
//            final RequestBody requestBody = RequestBody.create(mediaType, jsonObject.toString());
            FormBody formBody = new FormBody.Builder()
                    .add("username", username)
                    .add("password", password)
                    .build();
            Request request = new Request.Builder()
                    .post(formBody)
                    .url("https://www.wanandroid.com/user/login")
                    .build();
            OkHttpClient client = new OkHttpClient.Builder()
                    .cookieJar(HomeFragment.getCookieJar())
                    .build();
            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    Log.i("请求情况：", "请求失败");
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    if (response.isSuccessful()) {
                        Log.i("响应状态: ", "响应成功");
                        final String loginBody = response.body().string();
                        Gson gson = new Gson();
                        LoginBean loginBean = gson.fromJson(loginBody, LoginBean.class);
                        int loginResultCode = loginBean.getErrorCode();
                        Log.i("返回状态码: ", String.valueOf(loginResultCode));
                        if (loginResultCode == 0) {
                            Log.i("登录状态：", "登录成功" + loginBody);
//                            token = loginBean.getData();
                            SharedPreferences.Editor editor = getSharedPreferences("get_token", MODE_PRIVATE).edit();
                            editor.putString("username", loginBean.getData().getUsername());
//                            editor.putString("username", username);
                            editor.putString("password", password);
                            editor.putString("nickName", loginBean.getData().getNickname());
                            editor.putString("icon", loginBean.getData().getIcon());
                            editor.putInt("coinCount", loginBean.getData().getCoinCount());
                            editor.commit();
                            editor.apply();

                            MineFragment mineFragment = new MineFragment();
                            Message message = handler.obtainMessage();
                            message.obj = token;
                            handler.sendMessage(message);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_LONG).show();
//                                    finish();
                                }
                            });
                            loginStatus = 1;
                            SharedPreferences sSharedPreferences = getSharedPreferences("loginStatus", MODE_PRIVATE);
                            SharedPreferences.Editor sEditor = sSharedPreferences.edit();
                            sEditor.putInt("loginStatus", loginStatus);
                            sEditor.commit();

                            Intent intent = new Intent();
                            intent.setClass(LoginActivity.this, MainActivity.class);
                            intent.putExtra("flag", 3);
                            startActivity(intent);
                            LoginActivity.this.finish();

                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getApplicationContext(), "登录失败", Toast.LENGTH_LONG).show();
                                }
                            });
                        }

                    }
                }
            });
        }
    }
}
